import type { SelectOptionItem } from "/@/types/antd";
import { useI18n } from "/@/locales/useI18n";
import dayjs from "dayjs";

export function firstCharToUpper(str: string) {
  if (!str || typeof str != "string") return str;
  return str.replace(str[0], str[0].toUpperCase());
}

export function coverObj(
  originObj: { [key: string]: any },
  newObj: { [key: string]: any },
  cb?: (key: string, value: any) => any
) {
  for (const i in originObj) {
    const newValue = newObj[i];
    if (newValue !== undefined) {
      if (cb) {
        const result = cb(i, newValue);
        if (result !== undefined) {
          originObj[i] = result;
          continue;
        }
      }
      originObj[i] = newValue;
    }
  }
}

/**
 * 枚举类型数据转换为antd select options数据
 * @param enumData 枚举类型数据
 * @param localKey 对应locales中baseData中的key，若有值，则需要将label翻译
 * @returns antd select options数据
 */
export function enumToOptions(enumData: Record<string, any>, localKey?: string) {
  const result: SelectOptionItem[] = [];
  const { t } = useI18n();
  for (let key in enumData) {
    if (/^[\d]+$/.test(key)) continue;
    result.push({
      label: localKey ? t(`baseData.${localKey}.${key}`) : key,
      value: enumData[key],
    });
  }
  return result;
}

/**
 * 根据枚举类型数据获取指定value的item的label值
 * @param value antd select option的value值
 * @param enumData 枚举类型数据
 * @param localKey 对应locales中baseData中的key，若有值，则需要将label翻译
 * @returns {string | null} antd select label数据
 */
export function getLabelByValueFromEnum(value: string | number, enumData: Record<string, any>, localKey?: string) {
  const data = enumToOptions(enumData, localKey);
  const target = data.find((el) => el.value === value);
  return target ? target.label : null;
}

/**
 *
 * @param data  blob类型数据
 * @param fileName 导出文件名
 */
export function downloadFile(data: Blob, fileName?: string) {
  let blob = new Blob([data], { type: "application/vnd.ms-excel" });
  let url = URL.createObjectURL(blob);
  const link = document.createElement("a"); // 创建a标签
  link.href = url;
  link.download = fileName ? fileName : `导出文件`; // 重命名文件
  link.click();
  URL.revokeObjectURL(url); // 释放内存
}

export function isNullOrUndefOrEmpty(v) {
  return v === "" || v === undefined || v === null;
}

export function isEmptyObj(val) {
  if (typeof val !== "object" || !val) return false;
  for (const i in val) {
    return false;
  }
  return true;
}

export function isObj(val) {
  return Object.prototype.toString.call(val) === "[object Object]";
}

export function deepMergeObj(targetObj, newObj) {
  for (let i in newObj) {
    const val = newObj[i];
    if (isObj(val)) {
      const targetVal = targetObj[i];
      if (isObj(targetVal)) {
        deepMergeObj(targetVal, val);
      } else {
        targetObj[i] = val;
      }
    } else {
      targetObj[i] = val;
    }
  }
}

export function handleDateRowRender({ text }) {
  return text ? dayjs(text).format("YYYY-MM-DD HH:mm") : "--";
}
